<?php
/**
 * 飞信机器人--功能插件--开心辞典
 * 功能：仿开心辞典答题闯关类
 *      当前，每答对一题送1分
 *      答错n题后，自动终止，用户可以按 r 键，重新加始新一轮挑战（分数清0）
 * 数据表：fx_articles(存放题目，选项用|分隔，正确的答案后面加X)
 *                    如： 天鹅|娃娃鱼|孔雀|丹顶鹤X，丹顶鹤X 为正确答案 
 *        fx_game_kaixincidian_records：存放答题记录
 *        fx_game_kaixincidian_scores: 用户的分数
 * 作者： Kelvin
 * 联系： msn:shichangguo@msn.com, qq:191848423
*/
/*
支持参数(fx_menus表 extra_params字段)：
classid=分类id，
action=start： 开始闯关
action=queryscore：分数查询
*/


class GameKaiXinCiDian extends CommonPlugin
{
	var $UUID='4ddaef64-64ad-4f9a-8734-f179f68658f1';
	var $maxError = 2;
	var $scorePerQuestion = 1;
	
	public function GameKaiXinCiDian(&$session, $pid, $extraPara="")
	{
		parent::__construct($session, $pid, $extraPara);
	}
	
	private function setQuestionID($class_id,$question_id)
	{
		$this->set("{$class_id}_qid", $question_id);
	}

	private function getQuestionID($class_id)
	{
		$id = $this->getValue("{$class_id}_qid");
		return $id;
	}
	
	public function queryscore($class_id)
	{	
		return "您的当前分数：".$this->getScore($class_id)."\n"."系统最高分数:".$this->getMaxScore($class_id)."\n".$this->getFooter();	
	}
	
	public function getTips()
	{
		$class_id = $this->extraParam['classid'];
		$action = $this->extraParam['action'];
		if($action == 'queryscore')return $this->queryscore($class_id);
		
		return $this->newQuestion($class_id);
	}

	public function showQuestion($class_id, $question)
	{
		$msg = $question['title']."\n";
		$arr = explode('|', $question['content']);
	
		for($i=0; $i<count($arr); $i++)
		{
			$msg.='['.($i+1).'] '.str_replace('X','',$arr[$i])."\n";
		}
		return $msg;
	}
	
	public function getScore($class_id)
	{
		$sql = "select * from fx_game_kaixincidian_scores where buddy_id={$this->getBuddyID()} and class_id={$class_id}";
		$result = $this->query($sql);
		if(count($result)==0) return 0;
		
		return $result[0]['score'];	
	}
	
	public function getMaxScore($class_id)
	{
		$sql = "select max(score) as score from fx_game_kaixincidian_scores where class_id={$class_id}";
		$result = $this->query($sql);
		
		if(count($result)==0)return "无记录";
		
		return $result[0]['score'];		
	}
	public function newQuestion($class_id)
	{	
		//查看是否已经错过 maxError 题目, result=0：答错
		$sql = "select count(*) as count from fx_game_kaixincidian_records where buddy_id={$this->getBuddyID()} and class_id={$class_id} and result=0";
		$result = $this->query($sql);
		if( $result[0]['count'] > $this->maxError )
		{
			$maxScore = $this->getMaxScore($class_id);
			$myScore = $this->getScore($class_id);
			
			return "您已经错过{$this->maxError}次，本轮答题结束。系统最高分数--{$maxScore},您的得分--{$myScore}。您可以选择 r, 开始新的一轮挑战！".$this->getFooter(' r-重新挑战');
		}
			
		//查看用户是否有尚未答过的题目
		$questionID = $this->getQuestionID($class_id);
		if($questionID != 0 )
		{
			$sql = "select * from fx_game_kaixincidian_records where buddy_id={$this->getBuddyID()} and article_id=$questionID";
			$result = $this->query($sql);
			if( count($result) == 0 )
			{
				$sql = "select * from fx_articles where id=$questionID";
				$result = $this->query($sql);
				return "<b>继续您上次的答题</b>:)\n".$this->showQuestion($class_id, $result[0]). $this->getFooter(' 数字键--答题 r-重新挑战');
			}
		}
		//选出用户已经答过的题目
		$buddyID = $this->getBuddyID();
		$sql = "select article_id from fx_game_kaixincidian_records where buddy_id={$buddyID} and class_id={$class_id}";
		$result = $this->query($sql);
		//print_r($result);
		
		$cond = "";
		$num = count($result);
		for($i=0; $i<$num; $i++)
		{
			$cond .= $result[$i]['article_id'];
			if( $i!=($num-1) ) $cond.=",";
		}
		if($cond != "" )
		{
			$cond = " id not in($cond)";
		}
		
		//随机抽题
		$sql = "select * from fx_articles where class_id=$class_id";
		if($cond!="")$sql.=" and $cond";
		
		$sql .= " order by rand() limit 1";
		
		//echo $sql;
		
		$result = $this->query($sql);
		
		if(count($result) == 0 )return "已经没有可选的题目！".$this->getFooter(' r-重新挑战');
		
		$this->setQuestionID($class_id, $result[0]['id']);
		
		return $this->showQuestion($class_id, $result[0]). $this->getFooter('数字键--答题 r-重新挑战');
	}
	
	public function doQuestion($class_id,$input)
	{
		$input = intval($input);
		$questionID = $this->getQuestionID($class_id);
		
		$sql = "select * from fx_articles where id=$questionID";
		$result = $this->query($sql);
		if( count($result) == 0 )
		{
			return "系统错误，未发现该题目！".$this->getFooter();
		}
		
		$arr = explode('|', $result[0]['content']);
		if( $input<1 || $input > count($arr) )
		{
			return "输入错误，请重新选择".$this->getFooter();
		}
		
		$question = $arr[$input-1];
		
		$time = time(NULL);
		$buddyID = $this->getBuddyID();
		$value = 0;
		
		$msg = "您的回答错误，最多可以错{$this->maxError}次！继续下一题目！\n";
		if( substr($question, -1) == 'X')
		{
			// 正确
			$value = 1;
			$msg = "恭喜，您的回答正确！继续下一题目！\n";
			
			// 加分
			$sql = "select * from fx_game_kaixincidian_scores where buddy_id={$buddyID} and class_id={$class_id}";
			$result = $this->query($sql);
			if(count($result)==0)
			{
				$this->execute("insert into fx_game_kaixincidian_scores(buddy_id,class_id,score) values($buddyID,$class_id,{$this->scorePerQuestion})");
			}else 
			{
				$this->execute("update fx_game_kaixincidian_scores set score=score+1 where buddy_id=$buddyID and $class_id=$class_id");
			}
		}
		
		$sql = "insert into fx_game_kaixincidian_records(buddy_id,class_id,article_id,add_time,result)";
		$sql.= " values($buddyID,$class_id,$questionID,$time,$value)";
		$this->execute($sql);

		//清空题目记录
		$this->setQuestionID($class_id,0);	
		return $msg.$this->newQuestion($class_id);
	}
	
	public function handle($input)
	{
		if( parent::handleInput($input)) return false;
					
		$class_id = $this->extraParam['classid'];
		$action = $this->extraParam['action'];
		
		if( $action != 'start' )return "错误输入".$this->getFooter();

		if( $input == 'r' )
		{
			$this->setQuestionID($class_id, 0); //清空记录
			$buddy_id = $this->getBuddyID();
			$this->execute("delete from fx_game_kaixincidian_records where buddy_id={$buddy_id} and class_id={$class_id}");
			$this->execute("update fx_game_kaixincidian_scores set score=0 where buddy_id={$buddy_id} and class_id={$class_id}");
			return $this->newQuestion($class_id);
		}
		if( is_numeric($input) )
		{
			return $this->doQuestion($class_id,$input);
		}
		return "您的输入：".$input.$this->getFooter();
	}
}
?>